<template>
  <div class="app-container">
    <div>
      <el-button type="primary" size="small" @click="handleAddDic" icon="el-icon-plus">新增字典</el-button>
      <el-table
        :data="routes"
        style="width: 100%;margin-bottom: 20px;"
        row-key="value"
        border
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column label="字典名称">
          <template slot-scope="scope">{{ scope.row.label}}</template>
        </el-table-column>
        <el-table-column align="center" label="字典标识">
          <template slot-scope="scope">{{ scope.row.TypeCode }}</template>
        </el-table-column>
        <el-table-column align="center" label="排序">
          <template slot-scope="scope">{{ scope.row.Sort }}</template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleEdit(scope)" icon="el-icon-edit">编辑</el-button>
            <el-button type="text" size="mini" @click="addSubNode(scope)" icon="el-icon-plus">添加</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope)" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        :title="dialogType==='edit'?'编辑字典':'新增字典'"
        width="60%"
        top="10vh"
      >
        <el-form
          ref="model"
          :rules="rules"
          :label-position="labelPosition"
          :model="model"
          label-width="100px"
          style="width: 90%;"
        >
          <el-row>
            <el-col :span="12">
              <!-- <el-form-item label="父级字典" prop="ParentID">
                 <el-select v-model="model.ParentID" filterable placeholder="请选择">
                  <el-option
                    v-for="item in allRoutes"
                    :key="item.ID"
                    :label="item.TypeName"
                    :value="item.ID">
                  </el-option>
                </el-select>
              </el-form-item>-->
              <el-form-item label="父级字典" prop="ParentName">
                <el-input v-model="model.parentName" placeholder="请输入父级字典名称" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="codeVisible">
              <el-tooltip class="item" effect="dark" content="请确认,编辑时不可更改" placement="right-end">
                <el-form-item label="字典标识" prop="TypeCode">
                  <el-input v-model="model.TypeCode" placeholder="请输入字典标识" />
                </el-form-item>
              </el-tooltip>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="字典名称" prop="label"   >
                <el-input v-model="model.label" placeholder="请输入菜单名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序号" prop="Sort">
                <el-input-number v-model="model.Sort"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align:right;">
          <el-button type="danger" @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" @click="confirmModel">提交</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { deepClone } from "@/utils";
import {
  GetDictionaryitem,
  GetDictionaryall,
  deleteDic,
  addDic,
  existCode,
  updateDic
} from "@/api/dictionary";

const defaultModel = {
  ID: "",
  value: "",
  label: "",
  ParentID: "00000000-0000-0000-0000-000000000000",
  parentName: "顶级字典",
  TypeCode: "",
  TypeName: "",
  Sort: "",
  hasChildren: false,
  children: []
};

export default {
  filters: {
    typeFilter(type) {
      const typeMap = {
        1: "菜单",
        2: "按钮"
      };
      return typeMap[type];
    }
  },
  data() {
    return {
      filterText: "",
      model: Object.assign({}, defaultModel),
      routes: [],
      allRoutes: [],
      dialogVisible: false,
      codeVisible: false,
      dialogType: "new",
      typeOptions: [1, 2],
      labelPosition: "right",
      rules: {
        TypeCode: [{ required: true, message: "请输入标识码", trigger: "blur" }],
        label: [{ required: true, message: "请输入字典名名称", trigger: "blur" }],
        component: [
          { required: true, message: "请输入组件地址", trigger: "blur" }
        ],
        path: [{ required: true, message: "请输入菜单路由", trigger: "blur" }]
      }
    };
  },
  created() {
    this.GetAllDictionary();
    this.GetDictionary();
  },
  methods: {
    async GetDictionary() {
      const res = await GetDictionaryitem();
      this.routes = res.data;
    },
    async GetAllDictionary() {
      const res = await GetDictionaryall();
      this.allRoutes = res.data;
    },
    refresh() {
      this.GetDictionary();
    },
    handleDelete({ $index, row }) {
      if (row.children == null) {
        this.$confirm("确认删除 " + row.label + "?", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            this.goDelete(row.value);
          })
          .catch(err => {
            console.error(err);
          });
      } else {
        this.$message({
          type: "warning",
          message: "请先删除下面的子节点!"
        });
        return false;
      }
    },
    async goDelete(dicID) {
      let res = await deleteDic(dicID);
      if (res.code === 200) {
        if (res.data) {
          this.$notify({
            message: `删除成功`,
            type: "success",
            title: "成功",
            duration: 3000
          });
          this.GetDictionary();
        } else {
          this.$notify({
            message: res.message,
            type: "error",
            title: "失败",
            duration: 3000
          });
        }
      }
    },
    handleEdit(scope) {
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.codeVisible = false;
      this.model = deepClone(scope.row);
      this.model.parentID = scope.row.ParentID;
      this.model.parentName = scope.row.ParentName;
      this.$nextTick(() => {
        this.$refs["model"].clearValidate(); //清空上次的错误验证提示
      });
    },
    handleAddDic() {
      this.codeVisible = true;
      this.model = Object.assign({}, defaultModel);
      this.$nextTick(() => {
        this.$refs["model"].clearValidate(); //清空上次的错误验证提示
      });
      this.dialogType = "new";
      this.dialogVisible = true;
    },
    addSubNode(scope) {
      this.codeVisible = false;
      this.model = Object.assign({}, defaultModel);
      this.model.ParentID = scope.row.value;
      this.model.parentName = scope.row.label;
      this.$nextTick(() => {
        this.$refs["model"].clearValidate(); //清空上次的错误验证提示
      });
      this.dialogType = "new";
      this.dialogVisible = true;
    },
    async confirmModel() {
      //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
      var v;
      this.$refs["model"].validate(valid => {
        v = valid;
      });
      if (!v) {
        return false;
      }
      const isEdit = this.dialogType === "edit";
      if (isEdit) {
        await updateDic(this.model);
      } else {
        if (this.model.ParentID === "00000000-0000-0000-0000-000000000000") {
          let res = await existCode(this.model.TypeCode);
          if (res.code == 200) {
            if (!res.data) {
              this.$notify({
                message: "添加失败，此字典标识已存在，请更改",
                type: "error",
                title: "失败",
                duration: 3000
              });
              return;
            }
          }
        }
        await addDic(this.model);
      }
      this.GetDictionary();
      this.dialogVisible = false;
      this.$notify({
        message: `操作成功`,
        type: "success",
        title: "成功",
        duration: 3000
      });
    }
  }
};
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 12px;
}
</style>
